package com.cabal.ssh;

import com.cabal.auth.dao.CabalGatewayGameConfigMapper;
import com.cabal.auth.entity.CabalGatewayGameConfig;
import com.cabal.common.constants.SystemConstants;
import com.cabal.config.DynamicDataSourceContextHolder;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;

@Slf4j
@Service
public class SSHConnectionServiceImpl implements SSHConnectionService{

    // 47.113.224.21
    // 47.120.33.88
    private static String SSH_HOST = "47.113.224.21";

    private static int SSH_PORT = 18086;

    private static String SSH_USER = "root";

    //private static String PRIVATE_KEY_FILE_NAME = "cabal_server_aliyun_secret_1437_2023.pem";

    private static String PRIVATE_KEY_FILE_NAME = "cabal_server_aliyun_secret_2023.pem";

    @Resource
    private CabalGatewayGameConfigMapper cabalGatewayGameConfigMapper;

    @Override
    public void commandSSH(String command) {
        log.info("执行国战任务...");
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        CabalGatewayGameConfig cabalGatewayGameConfig = cabalGatewayGameConfigMapper.selectById(1);
        DynamicDataSourceContextHolder.removeContextKey();
        if(cabalGatewayGameConfig != null) {
            Integer nationWarOpen = cabalGatewayGameConfig.getNationWarOpen();
            if(nationWarOpen != null && nationWarOpen == 2) {
                log.info("国战任务配置为关闭，提前结束...");
                return;
            }
        }

        Session session = null;
        ChannelExec channelExec = null;

        try {
            JSch jsch = new JSch();

            // 如果私钥密码不为空，则需要使用以下方法加载私钥
            // jsch.addIdentity(privateKeyPath, passphrase);

            String privateKeyFile = System.getProperty("user.dir").concat("/template/").concat(PRIVATE_KEY_FILE_NAME);

            // 直接加载私钥，假设没有密码
            jsch.addIdentity(privateKeyFile);

            session = jsch.getSession(SSHConnectionServiceImpl.SSH_USER, SSHConnectionServiceImpl.SSH_HOST, SSHConnectionServiceImpl.SSH_PORT);

            // 设置密码（如果需要）
            // session.setPassword("your_password");

            // 建议设置SSH会话配置
            session.setConfig("StrictHostKeyChecking", "no");

            // 开启Session连接
            session.connect();

            log.info("Connected!");

            // 执行SSH命令
            //String command = "service WorldSvr_01_01 stop";
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);
            ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
            channelExec.setOutputStream(responseStream);
            channelExec.connect();

            // 等待命令执行完毕
            Thread.sleep(5000);
            String responseString = new String(responseStream.toByteArray());

            log.info(responseString);
            log.info("SSH远程操作结束...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.disconnect();
            }

            if (channelExec != null) {
                channelExec.disconnect();
            }
        }
    }

}
